package com.cb.activitytest;

public class chenbing_Circle_delete {
    public static class Node {
        String data;
        Node next;
    }

    public static void main(String[] args){
        Node head = new Node();
        head.data = "1";
        Node cur = head;

        for (int i = 2;i < 10;i++){
            Node node = new Node();
            node.data = i+"";
            cur.next = node;
            cur = node;
        }

        //删除倒数第5个
        int deleteN = 3;
        Node node = deleteInversePosition(head,deleteN);
        if (node != null) {
            System.out.println(node.data);
        }else {
            System.out.println("");
        }
    }

    private static Node deleteInversePosition(Node head,int position){
        Node current = head;
        //先计算node总个数
        int totalCount = 1;

        while (current.next != null){
            current = current.next;
            totalCount ++;
        }
        //如果删除位置大于总个数，则不进行删除操作
        if (totalCount< position){
            System.out.println("没有倒数第" + position+"个节点");
            return head;
        }

        //计算正向的删除位置，进行正向删除
        int deletePosition = totalCount-position+1;
        int currentPosition = 1;
        Node pre = null;
        current = head;
        while (current.next != null){
            if (deletePosition == 1){
                head = head.next;
                return head;
            }
            if (deletePosition == currentPosition){
                pre.next = current.next;
                return head;
            }else {
                pre = current;
                current = current.next;
                currentPosition ++;
            }
        }
        return head;
    }
}